/**
 * 
 */
this.playerHistoryList = new Array();
this.playerHistoryResultList = new Array();
this.opponentHistoryList = new Array();
this.opponentHistoryResultList = new Array();
this.historyHitList = new Array();
this.HistoryGameList = new Array();
var play = true;

var historyList = new Array();
var playerList = new Array();
var enemyList = new Array();

var count = 0;
var game;
var playerHistoryShipsHit = new Array();
var opponentHistoryShipsHit = new Array();
var enemyB = new Array();
var myBoard = new Array();
var timeouts = [];
/**
 * Hello world serer function, currently using "Esita uuesti" button
 * @ Only for testing!
 */
function replayRequest() {
	if (document.getElementById("newgame").innerHTML == "Alusta lahingut" || gameIsActive || selectedHistoryRowNr == -1){
		return;
	}
	play = true;
	count = 0;
	
	document.getElementById("newgame").innerHTML = "Tagasi";
	$('#newgame').click(function() {location.reload(true);});
	

	
	if (localStorage.battleShipHistory)
	{
		var object = jQuery.parseJSON(localStorage.battleShipHistory);
		HistoryGameList = new Array();
		for (i in object){
			HistoryGameList.push(new HistoryGame(object[i].player,object[i].opponent,
					object[i].playerHistoryString,object[i].playerHistoryResultListString,
					object[i].opponentHistoryString,object[i].opponentHistoryResultListString,
					object[i].historyHitListString));

		}
		game = HistoryGameList[selectedHistoryRowNr];
		
		historyList = jQuery.parseJSON(game.historyHitListString);
		playerList = jQuery.parseJSON(game.playerHistoryString);
		enemyList = jQuery.parseJSON(game.opponentHistoryString);
		
		reset(game);
		
		replay(game);
	}

}

function replay(game) {

	var i = count;
	var j = 0;
	while ( i < historyList.length){
		if (historyList[i] == "1"){
			timeouts.push(setTimeout(hitHistoryBoard, 1000*(j+1) ,playerList[i], 
					myBoard, jQuery.parseJSON(game.playerHistoryResultListString)[i], playerHistoryShipsHit));
		} else if (historyList[i] == "0"){
			timeouts.push(setTimeout(hitHistoryBoard, 1000*(j+1), enemyList[i], 
					enemyB, jQuery.parseJSON(game.opponentHistoryResultListString)[i], opponentHistoryShipsHit));
		}
		i++;
		j++;
	}
}
function forward(game){
	if (play){
		return;
	}
	var i = count;
	if (historyList[i] == "1"){
		hitHistoryBoard(playerList[i],myBoard, jQuery.parseJSON(game.playerHistoryResultListString)[i], playerHistoryShipsHit);
	} else if (historyList[i] == "0"){
		hitHistoryBoard(enemyList[i], enemyB, jQuery.parseJSON(game.opponentHistoryResultListString)[i], opponentHistoryShipsHit);
	}
}

function reset(game){
	
	drawHistoryGameBoards(game.player,game.opponent);
	
	enemyB = new Array();
	myBoard = new Array();
	
	var $arr = $(".playerHistory");
	$arr.each(function(i) {
	        enemyB.push($arr[i]); //add all squares to the enemyBoard list
	});
	var $arr = $(".enemyHistory");
	$arr.each(function(i) {
		myBoard.push($arr[i]); //add all squares to the fullBoard list
	});
	
	playerHistoryShipsHit = new Array();
	opponentHistoryShipsHit = new Array();
	
	for (var i = 0; i<12; i++){ //create empty hitlists for all ships
	    playerHistoryShipsHit.push([]);
	    opponentHistoryShipsHit.push([]);
	}
}

function backward(game){
	if (play || count < 1){
		return;
	}
	reset(game);

	
	var j = count-1;
	
	var i = 0;
	while ( i < j){
		if (historyList[i] == "1"){
			hitHistoryBoard(playerList[i],myBoard, jQuery.parseJSON(game.playerHistoryResultListString)[i], playerHistoryShipsHit);

		} else if (historyList[i] == "0"){
			hitHistoryBoard(enemyList[i], enemyB, jQuery.parseJSON(game.opponentHistoryResultListString)[i], opponentHistoryShipsHit);
		}
		i++;
	}
	count = j;
}


this.HistoryGame = function(player,opponent, playerHistoryString, playerHistoryResultListString, opponentHistoryString,opponentHistoryResultListString, historyHitListString){
	this.player = player;
	this.opponent = opponent;
	this.playerHistoryString = playerHistoryString;
	this.playerHistoryResultListString = playerHistoryResultListString;
	this.opponentHistoryString = opponentHistoryString;
	this.opponentHistoryResultListString = opponentHistoryResultListString;
	this.historyHitListString = historyHitListString;
	
};

HistoryGame.prototype.toString = function (){
	var string = "";
	string += this.player + "\n" + this.playerHistoryString + "\n"
	+ this.playerHistoryResultListString + "\n" + this.opponent + "\n" + this.opponentHistoryString + "\n" + this.opponentHistoryResultListString + "\n" 
	+ this.historyHitListString;
	
	return string;
};

this.saveGameToLocalStorage = function() {
	var playerHistoryString = JSON.stringify(playerHistoryList);
	var opponentHistoryString = JSON.stringify(opponentHistoryList);
	var historyHitListString = JSON.stringify(historyHitList);
	var opponentHistoryResultListString = JSON.stringify(opponentHistoryResultList);
	var playerHistoryResultListString = JSON.stringify(playerHistoryResultList);
	HistoryGameList = new Array();
	
	if (localStorage.battleShipHistory)
	{
		var object = jQuery.parseJSON(localStorage.battleShipHistory);
		for (i in object){
			HistoryGameList.push(new HistoryGame(object[i].player,object[i].opponent,
					object[i].playerHistoryString,object[i].playerHistoryResultListString,
					object[i].opponentHistoryString,object[i].opponentHistoryResultListString,
					object[i].historyHitListString));

		}
		HistoryGameList.push(new HistoryGame(client,opponentName,playerHistoryString, playerHistoryResultListString,
				opponentHistoryString,opponentHistoryResultListString,historyHitListString));

		localStorage.battleShipHistory=JSON.stringify(HistoryGameList);
	}
	else
	{
		HistoryGameList.push(new HistoryGame(client,opponentName,playerHistoryString, playerHistoryResultListString,
				opponentHistoryString,opponentHistoryResultListString,historyHitListString));
		localStorage.battleShipHistory=JSON.stringify(HistoryGameList);
	}
	
	playerHistoryList = new Array();
	opponentHistoryList = new Array();
	historyHitList = new Array();
	opponentHistoryResultList = new Array();
	playerHistoryResultList = new Array();
	
};


function drawHistoryGameBoards(clientName,opponentName) {
	
	var change = document.getElementById("main");
	
	var text ='<div id="player">'+clientName+'</div> <div id="opponent">'+opponentName+'</div>'; 

	var ids = ['A','B','C','D','E','F','G','H','I','J'];

	text += '<div id="myBoard" class="board">';
	text += "<table>";
    for (var i = 1; i < 11; i++) {
         for (var j = 0; j < 10; j++) {
        	  text += "<td id='"+i+ids[j]+"'class='playerHistory'></td>";
        }
         text += "</tr>";
    } 
    text += "</table> </div>";
    
    
    var ids = ['A','B','C','D','E','F','G','H','I','J'];
    text += '<div id="replayOpponent" class="board">';
    text += "<table>";
    for (var i = 1; i < 11; i++) {
         for (var j = 0; j < 10; j++) {
        	 text += "<td id='"+i+ids[j]+"'class='enemyHistory' onclick=''></td>";
        }
         text += "</tr>";
    } 
    if (play){
    	text += "</table> </div><div id='replayButton'><button type='button' id='playPause' onClick='switchPause()' class='pause'/>";
    } else{
    	text += "</table> </div><div id='replayButton'><button type='button' id='playPause' onClick='switchPause()' class='play'/>";
    }
    text += "<button type='button' id='forwards' onClick='forward(game)' class='forward'/><button type='button' id='backwards' onClick='backward(game)' class='backward'/></div>";

    change.innerHTML = text;

}



function switchPause() {
	if(play == false){
		$("#playPause").removeClass("play");
		$("#playPause").addClass("pause");
		play = true;
		replay(game);
		return;
	}
	if(play == true){
		$("#playPause").removeClass("pause");
		$("#playPause").addClass("play");
		for(var i=0; i<timeouts.length; i++) clearTimeout(timeouts[i]);
		timeouts = [];
		play = false;
	}
}


function hitHistoryBoard(square, board, result, shipshit) {

	if (square == "-" || result == "-1"){
		return;
	}
	count++;
	for (i in board) {
		if (board[i].id == square) {
			console.log(result);
			if (result>100){
				if (play == true){
					switchPause();
				}
				result -= 100;
				if(board == enemyB){
					document.getElementById("player").innerHTML = "V&otilde;itja";
				} else {
					document.getElementById("opponent").innerHTML = "V&otilde;itja";
				}
			}
			if (result == 0) {
				if (!$(board[i]).hasClass("hit")
						&& !$(board[i]).hasClass("sunk")) {
					$(board[i]).addClass("miss");
				}
			} else if (result == 1){
				$(board[i]).addClass("sunk");

			} else if (result > 1 && result <= 13) {
				
				result-=2;
				shipshit[result].push(board[i]); //when ship was hit store hit values to know when ship will be sunk
				$(board[i]).addClass("hit");
				
			} else if (result > 13) {
				
				result-=14;
				shipshit[result].push(board[i]);
				
				for (j in shipshit[result]) {

					for (k in board) {
						if (shipshit[result][j].id == board[k].id) {
							$(board[k]).addClass("sunk");
						}
					}
				}
			}
		}
	}

}